package calorie.com.calorie.activity;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioGroup;

import com.google.gson.Gson;
import com.ido.ble.BLEManager;
import com.ido.ble.LocalDataManager;
import com.ido.ble.bluetooth.device.BLEDevice;
import com.ido.ble.callback.BindCallBack;
import com.ido.ble.callback.ConnectCallBack;
import com.ido.ble.callback.GetDeviceInfoCallBack;
import com.ido.ble.callback.ScanCallBack;
import com.ido.ble.callback.SyncCallBack;
import com.ido.ble.data.manage.database.HealthActivity;
import com.ido.ble.data.manage.database.HealthBloodPressed;
import com.ido.ble.data.manage.database.HealthBloodPressedItem;
import com.ido.ble.data.manage.database.HealthHeartRate;
import com.ido.ble.data.manage.database.HealthHeartRateItem;
import com.ido.ble.data.manage.database.HealthSleep;
import com.ido.ble.data.manage.database.HealthSleepItem;
import com.ido.ble.data.manage.database.HealthSport;
import com.ido.ble.data.manage.database.HealthSportItem;
import com.ido.ble.protocol.model.ActivityDataCount;
import com.ido.ble.protocol.model.BasicInfo;
import com.ido.ble.protocol.model.BatteryInfo;
import com.ido.ble.protocol.model.HIDInfo;
import com.ido.ble.protocol.model.LiveData;
import com.ido.ble.protocol.model.NoticeSwitchInfo;
import com.ido.ble.protocol.model.SNInfo;
import com.ido.ble.protocol.model.SupportFunctionInfo;
import com.ido.ble.protocol.model.SystemTime;
import com.lxh.baselibray.BaseApplication;
import com.lxh.baselibray.base.XActivity;
import com.lxh.baselibray.util.ObjectUtils;
import com.lxh.baselibray.util.SPUtils;
import com.lxh.baselibray.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import calorie.com.calorie.R;
import calorie.com.calorie.adapter.MainFragmentPagerAdapter;
import calorie.com.calorie.constant.Constant;
import calorie.com.calorie.contact.GetAssetsContact;
import calorie.com.calorie.contact.SingleLoginContact;
import calorie.com.calorie.fragment.HomeFragment;
import calorie.com.calorie.fragment.MallFragment;
import calorie.com.calorie.fragment.MyWalletFragment;
import calorie.com.calorie.fragment.PersonCenterFragment;
import calorie.com.calorie.fragment.SportDataFragment;
import calorie.com.calorie.request.BaseResponce;
import calorie.com.calorie.response.AssertInfomationResponce;
import calorie.com.calorie.response.ResultDTO;
import calorie.com.calorie.response.UserAssets;
import calorie.com.calorie.util.BLEUpdateBroadcastReceiver;
import calorie.com.calorie.util.StaticValue;
import calorie.com.calorie.view.DownLoadDialogView;
import retrofit2.Response;

public class MainActivity extends XActivity implements RadioGroup.OnCheckedChangeListener, GetAssetsContact.IgetAssets, SingleLoginContact.ISingleLoginView {
    boolean isConnection = false;
    public static final String START_FLAG = "startFlag";
    public static BLEDevice myDevice;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.rg)
    RadioGroup rg;

    List<Fragment> fragmentList = new ArrayList<>();
    public static String bleAddress = "";
    public static boolean isFirstLogin = true;
    MainFragmentPagerAdapter adapter;
    SingleLoginContact.SingleLoginPresent singleLoginPresent;

    Handler handle = new Handler();
    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            handle.postDelayed(this, 4000);
            singleLoginPresent.loginHeartbeat(context);
        }
    };

    @Override
    public void initBeforView(Bundle savedInstanceState) {
        super.initBeforView(savedInstanceState);
        singleLoginPresent = new SingleLoginContact.SingleLoginPresent();
        singleLoginPresent.attach(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        handle.post(runnable1);
        int version = android.os.Build.VERSION.SDK_INT;
        if (version >= 23) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES, Manifest.permission.READ_EXTERNAL_STORAGE}, 127);
        }
        fragmentList.add(new HomeFragment());
        fragmentList.add(new MallFragment());
        fragmentList.add(new MyWalletFragment());
        fragmentList.add(new PersonCenterFragment());

        adapter = new MainFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                switch (i) {
                    case 0:
                        rg.check(R.id.rb_home);
                        break;
                    case 1:
                        rg.check(R.id.rb_mall);
                        break;
                    case 2:
                        rg.check(R.id.rb_my_wallet);
                        break;
                    case 3:
                        rg.check(R.id.rb_person_center);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        rg.setOnCheckedChangeListener(this);
        rg.getChildAt(0).performClick();


        calorie.com.calorie.contact.UpgradeContact.UpgradeContactPresent upgradeContactPresent = new calorie.com.calorie.contact.UpgradeContact.UpgradeContactPresent(new UpgradeContact());
        upgradeContactPresent.getUpgradeInfo();


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        String startFlag = getIntent().getStringExtra(START_FLAG);

        if ("login".equals(startFlag)) {
            viewPager.setCurrentItem(0);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_home:
                viewPager.setCurrentItem(0);
                break;
            case R.id.rb_mall:
                viewPager.setCurrentItem(1);
                break;
            case R.id.rb_my_wallet:
                viewPager.setCurrentItem(2);
                break;
            case R.id.rb_person_center:
                viewPager.setCurrentItem(3);
                break;

        }
    }

    private long timeMillis;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - timeMillis) > 2000) {
                ToastUtils.showLongToast(context, "再按一次退出");
                timeMillis = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);



            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onStop() {
        super.onStop();
        BLEManager.unregisterScanCallBack(scanCallBack);
        BLEManager.unregisterConnectCallBack(connectCallBack);//连接
        BLEManager.unregisterBindCallBack(bindCallBack);//绑定
        BLEManager.unregisterSyncHealthCallBack(iHealthCallBack);//数据同步
        BLEManager.unregisterSyncActivityCallBack(iActivityCallBack);
        BLEManager.unregisterGetDeviceInfoCallBack(iGetDeviceInfoCallBack);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BLEManager.registerScanCallBack(scanCallBack);
        BLEManager.registerConnectCallBack(connectCallBack);//连接
        BLEManager.registerBindCallBack(bindCallBack);//绑定
        BLEManager.registerSyncHealthCallBack(iHealthCallBack);//数据同步
        BLEManager.registerSyncActivityCallBack(iActivityCallBack);
        BLEManager.registerGetDeviceInfoCallBack(iGetDeviceInfoCallBack);
        int version = android.os.Build.VERSION.SDK_INT;
        if (version >= 23) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES, Manifest.permission.READ_EXTERNAL_STORAGE}, 127);
        }
        //  requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES,Manifest.permission.READ_EXTERNAL_STORAGE}, 127);
    }


    @Override
    protected void onRestart() {
        super.onRestart();

        BLEManager.registerScanCallBack(scanCallBack);
        BLEManager.registerConnectCallBack(connectCallBack);//连接
        BLEManager.registerBindCallBack(bindCallBack);//绑定
        BLEManager.registerSyncHealthCallBack(iHealthCallBack);//数据同步
        BLEManager.registerSyncActivityCallBack(iActivityCallBack);

        BLEManager.registerGetDeviceInfoCallBack(iGetDeviceInfoCallBack);
        int version = android.os.Build.VERSION.SDK_INT;
        if (version >= 23) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES, Manifest.permission.READ_EXTERNAL_STORAGE}, 127);
        }
        // requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES,Manifest.permission.READ_EXTERNAL_STORAGE}, 127);
        UserAssets userAssets = StaticValue.userAssets;
        if (userAssets.getBleAddress() != null && !userAssets.getBleAddress().equals("")) {
            boolean isConn = BLEManager.isConnected();
            if (!isConn) {
                BLEManager.stopScanDevices();
                BLEManager.startScanDevices();
            } else {
                isConnection = true;
                BLEManager.stopScanDevices();
                BLEManager.startSyncHealthData();
                BLEManager.startSyncActivityData();
                heartRateHandler.postDelayed(runnableGetheartRate, 0);
            }
        }


    }

    private SyncCallBack.IActivityCallBack iActivityCallBack = new SyncCallBack.IActivityCallBack() {
        @Override
        public void onStart() {
            // SportDataFragment.tv_synchronous_dataSYNC.setText("start sync activity data");
        }

        @Override
        public void onStop() {
            // SportDataFragment.tv_synchronous_dataSYNC.setText("sync activity data stop!");
        }

        @Override
        public void onSuccess() {
            // SportDataFragment.tv_synchronous_dataSYNC.setText("sync activity data success!");
        }

        @Override
        public void onFailed() {
            //  SportDataFragment.tv_synchronous_dataSYNC.setText("sync activity failed");
        }

        @Override
        public void onGetActivityData(HealthActivity healthActivity) {

        }
    };

    private GetDeviceInfoCallBack.ICallBack iGetDeviceInfoCallBack = new GetDeviceInfoCallBack.ICallBack() {
        @Override
        public void onGetBasicInfo(BasicInfo basicInfo) {

        }

        @Override
        public void onGetFunctionTable(SupportFunctionInfo supportFunctionInfo) {

        }

        @Override
        public void onGetTime(SystemTime systemTime) {

        }

        @Override
        public void onGetMacAddress(String s) {

        }

        @Override
        public void onGetBatteryInfo(BatteryInfo batteryInfo) {

        }

        @Override
        public void onGetSNInfo(SNInfo snInfo) {

        }

        @Override
        public void onGetNoticeCenterSwitchStatus(NoticeSwitchInfo noticeSwitchInfo) {

        }

        @Override
        public void onGetLiveData(LiveData liveData) {
            int num = liveData.heartRate;
            //这个数字要怎么显示到手机上
            if (num != 0) {
                //  heartRateHandler.removeCallbacks(runnableGetheartRate);
                SportDataFragment.heartRate = num;
            }

        }

        @Override
        public void onGetHIDInfo(HIDInfo hidInfo) {

        }

        @Override
        public void onGetActivityCount(ActivityDataCount activityDataCount) {

        }
    };

    Handler heartRateHandler = new Handler();
    Runnable runnableGetheartRate = new Runnable() {
        @Override
        public void run() {


            BLEManager.getLiveData();
            heartRateHandler.postDelayed(this, 2000);

        }
    };

    public BindCallBack.ICallBack bindCallBack = new BindCallBack.ICallBack() {
        @Override
        public void onSuccess() {

            //修改用户蓝牙信息到服务器
            BLEUpdateBroadcastReceiver.bracelet_view.setText("绑定成功");
            BLEManager.startSyncHealthData();//开始同步数据
            BLEManager.startSyncActivityData();//开始同步数据
            heartRateHandler.postDelayed(runnableGetheartRate, 0);
        }

        @Override
        public void onFailed(BindCallBack.BindFailedError bindFailedError) {
            BLEUpdateBroadcastReceiver.bracelet_view.setText("绑定失败");
        }

        protected void closeProgressDialog() {

        }

        @Override
        public void onCancel() {
            closeProgressDialog();

        }

        @Override
        public void onReject() {
            closeProgressDialog();

        }

        @Override
        public void onNeedAuth() {

        }
    };


    private SyncCallBack.IHealthCallBack iHealthCallBack = new SyncCallBack.IHealthCallBack() {
        @Override
        public void onStart() {
            BLEUpdateBroadcastReceiver.bracelet_view.setText("正在同步数据");
        }

        @Override
        public void onProgress(int progress) {
            updateProgress.removeCallbacks(runnable);
            BLEUpdateBroadcastReceiver.bracelet_view.setText("正在同步数据：" + progress + "%");
            BLEUpdateBroadcastReceiver.bracelet_view.setTag(null);
        }

        @Override
        public void onStop() {
            BLEUpdateBroadcastReceiver.bracelet_view.setText("停止同步数据");
        }

        @Override
        public void onSuccess() {

            BLEUpdateBroadcastReceiver.bracelet_view.setText("点击获取数据");
            updateProgress.removeCallbacks(runnable);
            BLEUpdateBroadcastReceiver.bracelet_view.setTag(0);
            BLEUpdateBroadcastReceiver.bracelet_view.setEnabled(true);
        }

        @Override
        public void onFailed() {
            BLEUpdateBroadcastReceiver.bracelet_view.setText("数据同步失败");
            BLEUpdateBroadcastReceiver.bracelet_view.setTag(0);
            BLEUpdateBroadcastReceiver.bracelet_view.setEnabled(true);
        }

        @Override
        public void onGetSportData(HealthSport healthSport, List<HealthSportItem> items) {

        }

        @Override
        public void onGetSleepData(HealthSleep healthSleep, List<HealthSleepItem> items) {

        }

        @Override
        public void onGetHeartRateData(HealthHeartRate healthHeartRate, List<HealthHeartRateItem> items) {

        }

        @Override
        public void onGetBloodPressureData(HealthBloodPressed healthBloodPressed, List<HealthBloodPressedItem> items) {

        }
    };
    public ConnectCallBack.ICallBack connectCallBack = new ConnectCallBack.ICallBack() {

        @Override
        public void onConnectStart() {

        }

        @Override
        public void onConnecting() {

        }

        @Override
        public void onConnectSuccess() {
            //连接成功D的时候直接绑定
            Log.e("connect success", "");
            BLEManager.bind();
            // getSportData();//成功后，绑定
            BLEUpdateBroadcastReceiver.bracelet_view.setText("蓝牙绑定中");


        }

        @Override
        public void onConnectFailed() {

            //  SportDataFragment.tv_synchronous_dataSYNC.setText("蓝牙连接失败");
            //  SportDataFragment.tv_synchronous_dataSYNC.setText("点击重新连接");
        }

        @Override
        public void onConnectBreak() {

        }

        @Override
        public void onInDfuMode(BLEDevice bleDevice) {

        }

        @Override
        public void onInitCompleted() {
        }

    };


    public ScanCallBack.ICallBack scanCallBack = new ScanCallBack.ICallBack() {
        @Override
        public void onStart() {
            BLEUpdateBroadcastReceiver.bracelet_view.setText("蓝牙扫描中");
            updateProgress.postDelayed(runnable, 0);
        }

        @Override
        public void onFindDevice(BLEDevice device) {


            if (bleAddress != null && !bleAddress.equals("") && bleAddress.equals(device.mDeviceAddress)) {
                isConnection = true;
                BLEUpdateBroadcastReceiver.bracelet_view.setText("蓝牙连接中");
                if (LocalDataManager.isBind()) {
                    BLEManager.autoConnect();
                    return;
                }
                BLEManager.connect(device);//找到我已经绑定的设备，连接
                Log.e("connection。。。。", device.mDeviceAddress);


            }
        }

        @Override
        public void onScanFinished() {
            if (!isConnection) {
                ToastUtils.showLongToast(context, "没有找到您绑定的设备");
                BLEUpdateBroadcastReceiver.bracelet_view.setText("点击重新扫描");
                BLEUpdateBroadcastReceiver.bracelet_view.setTag("1");
                BLEUpdateBroadcastReceiver.bracelet_view.setEnabled(true);
                updateProgress.removeCallbacks(runnable);
            }

        }
    };

    @Override
    public void getAssetsResult(Response<AssertInfomationResponce> response) {
        if (response.body().getCode() == Constant.SUCCESS_CODE) {

            Gson gs = new Gson();
            StaticValue.userAssets = gs.fromJson(gs.toJson(response.body().getData()), UserAssets.class);//保存用户资产信息
            SPUtils.putString(Constant.POWERNUM,StaticValue.userAssets.getPowerNum(),context);
            UserAssets userAssets = StaticValue.userAssets;
            BLEUpdateBroadcastReceiver.setAssets(userAssets);
            if (userAssets != null && userAssets.getBleAddress() != null && !userAssets.getBleAddress().equals("")) {
                bleAddress = userAssets.getBleAddress();
                Boolean is = BLEManager.isBind();
                is = BLEManager.isConnected();
                if (isFirstLogin) {
                    BLEManager.stopScanDevices();
                    BLEManager.startScanDevices();
                    isFirstLogin = false;
                }
                SPUtils.putString(Constant.BLEADDRESS, userAssets.getBleAddress(), context);
                SPUtils.putString(Constant.BLENAME, userAssets.getBleName(), context);//保存手环信息
            } else if (userAssets.getBleAddress() == null || userAssets.getBleAddress().equals("")) {
                BLEUpdateBroadcastReceiver.bracelet_view.setText("手环还没有绑定");
                BLEUpdateBroadcastReceiver.bracelet_view.setTag("2");
                BLEUpdateBroadcastReceiver.bracelet_view.setEnabled(true);
                SPUtils.putString(Constant.BLEADDRESS, "", context);
                SPUtils.putString(Constant.BLENAME, "", context);//保存手环信息
            }
        } else if (response.body().getCode() == 201) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            this.finish();
        }
    }


    Handler updateProgress = new Handler();
    Runnable runnable = new Runnable() {
        private int num = 0;

        @Override
        public void run() {
            String text = BLEUpdateBroadcastReceiver.bracelet_view.getText().toString();
            num++;
            text += "·";
            if (num >= 5) {
                text = text.replace("·", "");
            }
            BLEUpdateBroadcastReceiver.bracelet_view.setText(text);

            updateProgress.postDelayed(this, 400);
        }
    };


    @Override
    public void loginHeartbeatResult(Response<BaseResponce> response) {
        if (response.body().getCode() == 202) {
            handle.removeCallbacks(runnable1);
            //弹出提示用户帐号在其它地方登录
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    final Activity taskTop = BaseApplication.getActivityManage().getTaskTop();
                    if (ObjectUtils.isEmpty(taskTop)) return;
                    AlertDialog dialog = null;
                    AlertDialog.Builder builder = new AlertDialog.Builder(taskTop)
                            .setCancelable(false)
                            .setMessage("您的帐号在其它终端登录，请注意账号安全")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    clearData();
                                    taskTop.startActivity(new Intent(taskTop, LoginActivity.class));
                                    BaseApplication.getActivityManage().finishAll();
                                    dialog.dismiss();
                                }
                            });
                    dialog = builder.create();
                    if (!dialog.isShowing()) {
                        dialog.show();
                    }
                }
            });


        }


    }

    private void clearData() {
        SPUtils.putInt(Constant.USER_ID, -1, context);
        SPUtils.putString(Constant.PHONE, null, context);
        SPUtils.putString(Constant.INVITE_CODE, null, context);
        SPUtils.putString(Constant.LOGIN_PWD, null, context);
        SPUtils.getString(Constant.NICK_NAME, null, context);
        SPUtils.getString(Constant.ACCOUNT, null, context);
        SPUtils.getString(Constant.RECEIVE_ADDRESS, null, context);
        SPUtils.getString(Constant.PURSE_ADDRESS, null, context);
        SPUtils.getString(Constant.LOGIN_TIME, null, context);
        StaticValue.user = null;
        StaticValue.userAssets = null;
    }

    //检测是否需要升级
    public class UpgradeContact implements calorie.com.calorie.contact.UpgradeContact.IUpgradeContact {

        @Override
        public void getVersionResult(Response<ResultDTO> response) {
            try {
                Log.e("版本号是：", response.body().getData().toString());

                int versionCode = context.getPackageManager().
                        getPackageInfo(context.getPackageName(), 0).versionCode;//得到版本号

                if (versionCode < Integer.parseInt(response.body().getData().toString())) {//本地的版本号比服务器的要低
                    //启动下载，更新app
                    Log.e("msg", "下载最新的APP");
                    DownLoadDialogView downLoadDialogView = new DownLoadDialogView(context, R.style.down_dialog_style);
                    Window window = downLoadDialogView.getWindow();
                    //设置边框距离
                    window.getDecorView().setPadding(0, 0, 0, 0);
                    WindowManager.LayoutParams lp = window.getAttributes();
                    //设置宽高
                    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                    lp.height = 800;
                    window.setAttributes(lp);
                    //设置点击Dialog外部任意区域关闭Dialog
                    // downLoadDialogView.setCanceledOnTouchOutside(false);
                    downLoadDialogView.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}


